package com.isoft.c2team3service2.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class WebUtils {
    /**
     * 将对象以json格式数据写入到客户端
     */
    public static boolean renderObj(HttpServletResponse response , Object obj) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
            String objStr = new ObjectMapper().writeValueAsString(obj) ;  // 把对象转换为json字符串
            response.getWriter().print(objStr);
            return true ;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false ;
    }
    /**
     * 将字符串写入到客户端
     */
    public static String renderString(HttpServletResponse response , String str) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
            response.getWriter().print(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null ;
    }
}
